﻿<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title></title>
    <link href="../Resource/CSS/site.css" rel="stylesheet" />
    <link href="../Resource/CSS/jquery-ui-1.10.4.custom.min.css" rel="stylesheet" />
    <script src="../Resource/JS/jquery-1.10.2.js"></script>
    <script src="../Resource/JS/jquery-ui-1.10.4.custom.min.js"></script>
    <script src="../Resource/JS/angular.1.2.0.min.js"></script>
    <script src="../Resource/JS/jquery.ui.datepicker-zh-CN.js"></script>
    <script src="../Resource/JS/webSQL.js"></script>
</head>
<body ng-app="book">
    <!-- <div ng-controller="bookToolbar">
    </div>-->

    <div ng-controller="bookController">
        <input type="button" ng-click="getData();" value="LoadData" />
        <input type="button" ng-click="addBook();" value="Add" />
        <input type="button" ng-click="editBook();" value="Update" />
        <input type="button" ng-click="deleteBook();" value="Delete" />
        <br />
        search by name:<input type="text" ng-model="seaTxt" />

        <table class="tab">
            <tr>
                <td>
                    <input type="checkbox" name="checkAll" ng-model="ck" ng-click="chooseAll($event);" /></td>
                <td>Id</td>
                <td>Name</td>
                <td>Date</td>
                <td>Money</td>
            </tr>
            <tbody ng-repeat="item in books">
                <tr>
                    <td>
                        <input type="checkbox" name="checkOne" ng-model='item.ck' /></td>
                    <td>{{item.id}}</td>
                    <td remove-filename>{{item.name}}</td>
                    <td>{{item.date}}</td>
                    <td>{{item.money}}</td>
                </tr>
            </tbody>
        </table>

        <show-dialog></show-dialog>
    </div>

</body>
</html>
<script>
    var tag = "";
    var app = angular.module("book", [], function () { });

    app.directive("datePicker", function () {
        return {
            restrict: "EA",
            replace: true,
            template: "<input type='text' id='txt_Date' ng-model='item.date' />",
            link: function (scope, element, attrs, ctrl) {
                $(element).datepicker({
                    changeMonth: true,
                    changeYear: true,
                    dateFormat: 'yy-MM-dd',
                    showButtonPanel: true,
                    onSelect: function (dateText, inst) {
                        scope.item.date = dateText;
                    }
                });
            },
            controller: function ($scope, $element) {
                var s = $scope.item;
            }
        }
    });

    app.directive("removeFilename", function () {
        return {
            restrict: "A",
            link: function (scope, element, attrs, ctrl) {

                //scope.$on('changeData', function (e,item) {
                //    var v = item.name;
                //    if (attrs.removeFilename == "delay") {
                //        setTimeout(function () {
                //            $(element).text(cutStr(v));
                //        }, 100);
                //    } else {
                //        $(element).text(cutStr(v));
                //    }
                //})

                function cutStr(str) {
                    if (!str) {
                        return;
                    }
                    else if (str.indexOf('.') == -1 || str.trim().split('.').length > 2) {
                        return str;
                    }
                    else {
                        return str.substring(0, str.indexOf('.'));
                    }
                }
                if (scope.item && scope.item.name) {
                    var v = scope.item.name;

                    if (attrs.removeFilename == "delay") {
                        setTimeout(function () {
                            $(element).text(cutStr(v));
                        }, 100);
                    } else {
                        $(element).text(cutStr(v));
                    }
                }
            }
        }
    });

    app.directive('showDialog', function () {
        var temp = {
            restrict: "E",
            template: "<div id='select' ng-if='openDialog'><table id='tab' class='tab'><tr><td>Id:</td><td><input type='text' ng-model='item.id' /></td></tr>" +
                "<tr><td>Name:</td><td><input type='text' ng-model='item.name' /></td></tr>" +
                "<tr><td>Date:</td><td><date-picker></date-picker></td></tr>" +
                "<tr><td>Money:</td><td><input type='text' ng-model='item.money' /></td></tr>" +
                "<tr><td colspan='2'><input id='confirm' class='btn_n' type='button'  value='确认' ng-click='save()' />" +
                "<input id='confirm' class='btn_n' type='button' value='关闭' ng-click='close()' />" +
                "</td></tr></table></div><div id='black' ng-if='openDialog'></div>",
            controller: function ($scope, $element, $rootScope) {
                $scope.openDialog = false;
                $scope.save = function () {
                    $rootScope.$broadcast('saveData', $scope.item);
                    $scope.openDialog = false;
                }
                $scope.$on("updateData", function (e, item) {
                    $scope.item = {
                        ck: true,
                        name: item.name,
                        id: item.id,
                        date: item.date,
                        money: item.money
                    };
                });
                $scope.close = function () {
                    $scope.openDialog = false;
                    $scope.item = {};
                }
            }
        };
        return temp;
    });

    app.factory("dataManager", [function () {
        var Manager = function () {
            webStorage.webSql.apply(this, []);
        }
        Manager.prototype.init = function () {
            this.openDatabase();
            this.createTable();
        }
        Manager.prototype.query = function () {
            this.query();
        }
        Manager.prototype.insert = function (obj) {
            this.insert(obj);
        }
        Manager.prototype.update = function (obj) {
            this.update(obj);
        }
        Manager.prototype.delItem = function (obj) {
            this.delItem(obj);
        }
        Manager.prototype.delItems = function (items) {
            for (var i = 0; i < items.length; i++) {
                this.delItem(items[i]);
            }
        }
        return Manager;
    }]);

    app.factory("tools", [function () {
        return {
            delItems: function (delData, data) {
                var res = [];
                for (var i = 0; i < data.length; i++) {
                    var exist = false;
                    for (var j = 0; j < delData.length; j++) {
                        if (data[i].id == delData[j].id) {
                            exist = true;
                        }
                    }
                    if (!exist) {
                        res.push(data[i]);
                    }
                }
                return res;
            }
        }
    }])

    app.factory("Book", ["tools", "dataManager", function (tools, dataManager) {
        var data_manager = new dataManager();
        data_manager.init();

        var BookManager = function () {
            this.book = { id: '', name: '', date: '', money: '', ck: '' };
            this.books = [];
        }

        BookManager.prototype.getBooks = function () {
            data_manager.query();
            var that = this;
            setTimeout(function () { that.books = that.convertData(data_manager.d); }, 100);
        }

        BookManager.prototype.getBookById = function (id) {
            var res = null;
            for (var i = 0; i < this.books.length; i++) {
                if (id == this.books[i].id) {
                    res = this.books[i];
                }
            }
            return res;
        }

        BookManager.prototype.addBook = function (book, books) {
            data_manager.insert(book);
            books.push(book);
        }

        BookManager.prototype.updateBook = function (book, books) {
            data_manager.update(book);
            for (var i = 0; i < books.length; i++) {
                if (book.id == books[i].id) {
                    for (var k in book) {
                        books[i][k] = book[k];
                    }
                }
            }
        }

        BookManager.prototype.searchBook = function (name, books) {
            var res = [];
            for (var i = 0; i < books.length; i++) {
                if (books[i].name.indexOf(name) != -1) {
                    res.push(books[i]);
                }
            }
            return res;
        }

        BookManager.prototype.delItems = function (dbooks, books) {
            data_manager.delItems(dbooks);
            return tools.delItems(dbooks, books);
        }

        BookManager.prototype.ChooseItems = function (status, books) {
            var res = [];
            for (var i = 0; i < books.length; i++) {
                books[i].ck = status;
                res.push(books[i]);
            }
            return res;
        }

        BookManager.prototype.getChooseItems = function (books) {
            var res = [];
            for (var i = 0; i < books.length; i++) {
                if (books[i].ck) {
                    res.push(books[i]);
                }
            }
            return res;
        }

        BookManager.prototype.convertData = function (data) {
            var arr = [];
            for (var i = 0; i < data.length; i++) {
                var j = { ck: false, id: data.item(i)['id'], name: data.item(i)['name'], money: data.item(i)['money'], date: data.item(i)['date'], tag: Math.random() };
                arr.push(j);
            }
            return arr;
        }

        return BookManager;
    }]);

    app.controller("bookController", function ($scope, Book, $rootScope) {
        var manager = new Book();
        manager.getBooks();

        $scope.getData = function () {
            $scope.books = manager.books;
        }

        $scope.seaTxt = "";
        $scope.$on('saveData', function (e, item) {
            if (tag == "add") {
                manager.addBook(item, $scope.books);
            } else {
                manager.updateBook(item, $scope.books);
                $scope.$broadcast("changeData", item);
            }

            $scope.openDialog = false;
        })
        $scope.ck = false;
        $scope.chooseAll = function (e) {
            if (!$scope.books) {
                alert("Load Data First!");
                return;
            }

            $scope.books = manager.ChooseItems(!$scope.ck, $scope.books);
        }
        $rootScope.items = [];
        $scope.addBook = function () {
            tag = "add";
            $scope.item = {};
            $scope.openDialog = true;
        }

        $scope.$watch("books", function (n, o) {
            if (o == undefined || n == undefined) {
                return;
            }
            if (n == o) {
                return;
            }
            var _d = $scope.books;
            var chooseArr = [];
            for (var i = 0; i < _d.length; i++) {
                if (_d[i].ck) {
                    chooseArr.push(1);
                }
            }
            $scope.ck = chooseArr.length == $scope.books.length;
        }, true);

        $scope.editBook = function () {
            var cks = manager.getChooseItems($scope.books);

            if (cks.length > 1 || cks.length == 0) {
                alert("choose one!");
                return;
            }
            $scope.openDialog = true;
            $scope.item = cks[0];

            $rootScope.$broadcast('updateData', $scope.item);
            tag = "edit";
        }

        $scope.deleteBook = function () {
            var res = manager.getChooseItems($scope.books);
            if (res.length == 0) {
                alert("choose one!");
                return;
            }
            $scope.books = manager.delItems(res, $scope.books);
        }

        $scope.$watch("seaTxt", function (n, o) {
            if (!$scope.books) {
                return;
            }
            if (manager.books) {
                if (n == "") {
                    $scope.books = manager.books;
                } else {
                    $scope.books = manager.searchBook($scope.seaTxt, manager.books);
                }
            }
        })
    })
</script>
